package com.be.beadmin.device.controller;

import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.device.entity.DeFile;
import com.be.beadmin.device.dto.output.DeFileEx;
import com.be.beadmin.device.entity.EhsFile;
import com.be.beadmin.device.repository.DeFileRepository;
import com.be.beadmin.device.repository.EhsFileRepository;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Page;

import com.be.beadmin.device.service.DeFileService;
import com.be.beadmin.device.dto.input.DeFileQueryCriteria;
import com.be.beadmin.device.dto.input.DeFileDto;
import org.springframework.data.domain.Pageable;
import com.be.beadmin.common.utils.ResultModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.io.IOException;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;

/**
* @author chenxu
* @date 2023-11-12
**/
@RestController
public class DeFileController {

    @Autowired
    private  DeFileService deFileService;
    @Autowired
    private DeFileRepository deFileRepository;
    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    private String bucketName = "defile";


    @PostMapping(value = "/device/getDeFileByPage")
    public ResultModel getDeFileByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(deFileService.getDeFileByPage(pageEntity)) ;
    }

    @PostMapping("/device/addDeFile")
    public ResultModel addDeFile(@RequestBody DeFileDto deFileDto){
        deFileService.addDeFile(deFileDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/device/delDeFile")
    public ResultModel delDeFile(@RequestBody DeFileDto deFileDto){
        deFileService.delDeFile(deFileDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/device/updateDeFile")
    public ResultModel updateDeFile(@RequestBody DeFileDto deFileDto){
        deFileService.updateDeFile(deFileDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/device/exportDeFile")
    public void exportDeFile(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<DeFileEx> deFilePage = deFileService.getDeFileByPage(pageEntity);
        List<DeFileEx> deFileExes = deFilePage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("DeFile接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DeFileEx.class).sheet("sheet1").doWrite(deFileExes);
    }



    @ApiOperation("de新增附件信息")
    @PostMapping("/device/uploaddeFile")
    public ResultModel uploaddeFile(
            @ApiParam(value = "附件",required = true) @RequestParam("file") MultipartFile[] multipartFiles,
            @ApiParam(value = "deitem_id",required = true) @RequestParam String deitemId,
            @ApiParam(value = "文件名称") @RequestParam String fileName,
            @ApiParam(value = "备注") @RequestParam(required = false) String memo)  {
        try {
            deFileService.uploadDeFile(deitemId, multipartFiles, fileName, memo, bucketName);
            return ResultModel.success(ResultModel.ADD);
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }

    }

    @ApiOperation("de附件下载")
    @GetMapping("/device/DedownloadDeFile")
    public ResultModel downloadFile(@ApiParam(value = "附件id")@RequestParam String id,
                                    HttpServletResponse response) throws Exception {
        try {

            DeFile deFile = deFileRepository.findDeFileByIdAndDelete(id, 0);
            //System.out.println(deFile.getBucketName());
            //System.out.println(deFile.getFileName());
            String fileName = deFile.getFileName();
            String bucketName = deFile.getBucketName();
            String version =deFile.getVersion();
            String fileCode = deFile.getFileCode();
            String downloadFileName= fileCode+"+"+String.valueOf(version)+"+"+fileName;
            InputStream inputStream = minioService.downloadOne(bucketName, downloadFileName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Disposition", "attachment;filename="+downloadFileName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            return  ResultModel.success("下载成功");
        } catch (Exception e) {
            return ResultModel.error(99,"文件读取异常");
        }
    }
    @ApiOperation("de附件下载2")
    @PostMapping("/device/downloadDeFile2")
    public ResultModel downloadFile2(@ApiParam(value = "附件id")@RequestParam String id,
                                     HttpServletResponse response) throws Exception {
        deFileService.downloadDeFile(id,response);
        return null;

    }

    @ApiOperation("de附件预览")
    @PostMapping("/device/previewDeFile")
    public ResultModel getFilePreviewUrl(@ApiParam(value = "附件id",required = true) @RequestParam String id)throws Exception{
        return ResultModel.success(deFileService.previewDeFile(id));
    }



}